#include "MarsPrecompile.h"

#include "MarsMaterialMgr.h"
#include "MarsFileSysMgr.h"
#include "MarsMaterial.h"

#include "json/json.h"

using namespace Graphics;

//////////////////////////////////////////////////////////////////////////
static const char* const DEFAULT_MATERIAL_FILENAME = "default.mat";
static const char* const DEFAULT_MATERIAL_NAME = "default";

static Material ls_defaultMat;

MaterialMgr* Singleton< MaterialMgr >::ms_pInstance = NULL;

MaterialMgr::MaterialMgr()
{

}

MaterialMgr::~MaterialMgr()
{

}

bool MaterialMgr::Initialize()
{
	LoadMaterial( DEFAULT_MATERIAL_FILENAME, DEFAULT_MATERIAL_NAME );
	return true;
}

void MaterialMgr::Shutdown()
{

}

Material& MaterialMgr::CreateMaterial( const std::string& name )
{
	Material* pMat = NULL;

	if ( m_mapMaterials.find( name ) != m_mapMaterials.end() ) 
	{
		pMat = m_mapMaterials[ name ];
	}
	else
	{
		pMat = new Material();
		m_mapMaterials.insert( std::make_pair( name, pMat ) ); 
	}

	return ( *pMat );
}

Material& MaterialMgr::CopyMaterial( const Material& mat, const std::string& name )
{
	Material& rMat = CreateMaterial( name );

	return ( rMat );
}

const Material& MaterialMgr::LoadMaterial( const std::string& filename, const std::string& name )
{
	std::string strContent;
	if ( !FileSysMgr::Instance().LoadFileContent( filename, strContent ) )
	{
		return ls_defaultMat;
	}

	Json::Value root;
	Json::Reader reader( Json::Features::all() );
	std::string stdContent = strContent;
	bool parsingSuccessful = reader.parse( stdContent, root );
	if ( !parsingSuccessful )
	{
		return ls_defaultMat;
	}

	Material& rMat = CreateMaterial( name );

	return ( rMat );
}

const Material& MaterialMgr::GetMaterial( const std::string& name )
{
	if ( m_mapMaterials.find( name ) != m_mapMaterials.end() ) 
	{
		return ( *m_mapMaterials[ name ] );
	}
	else
	{
		return ls_defaultMat;
	}
}
